package com.example.springboot1.socket;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author zhangwen
 * @description 消息时间
 * @date 2019-1-23 11:09
 */
@Component
@Order(1)
@Slf4j
public class MessageEventHandler {
    //存储SocketIOClient，用于广播
    public static ConcurrentMap<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>();

    private final SocketIOServer socketIOServer;


    @Autowired
    public MessageEventHandler(SocketIOServer socketIOServer) {
        this.socketIOServer = socketIOServer;
    }

    @OnConnect
    public void connect(SocketIOClient client) {
        String token = client.getHandshakeData().getSingleUrlParam("token");
        String plat = client.getHandshakeData().getSingleUrlParam("plat");
        String id = client.getHandshakeData().getSingleUrlParam("id");
        //存储SocketIOClient
        socketIOClientMap.put(id, client);
        //回发消息
        client.sendEvent("message", "onConnect back");
        System.out.println("客户端:" + client.getSessionId() + "已连接,id=" + id);
        log.info("连接成功");

    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        System.out.println("客户端:" + client.getSessionId() + "断开连接");
     }


    /**
     * 客户端事件
     *
     * @param client  　客户端信息
     * @param request 请求信息
     * @param data    　客户端发送数据
     */
    @OnEvent(value = "messageevent")
    public void onEvent(SocketIOClient client, AckRequest request, Message data) {
        System.out.println("发来消息：" + data.getMsg());
        //回发消息
        client.sendEvent("messageevent", "我是服务器发来的信息");
        //广播消息
        sendBroadcast();
    }

    /**
     * 广播消息
     */
    public void sendBroadcast() {
        for (SocketIOClient client : socketIOClientMap.values()) {
            if (client.isChannelOpen()) {
                client.sendEvent("Broadcast", "当前时间:" + new Date(System.currentTimeMillis()));
            }
        }

    }



}
